package com.cy.config;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.cy.service.impl.VerifyServiceImpl;
import com.cy.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 角色权限检查切面
 */
@Aspect
@Component
public class RoleCheckAspect {
    private final HttpServletRequest request;

    public RoleCheckAspect(HttpServletRequest request) {
        this.request = request;
    }

    @Around("@annotation(requiresRole)") // 拦截带有 @RequiresRole 注解的方法
    public Object checkRole(ProceedingJoinPoint joinPoint, RequiresRole requiresRole) throws Throwable {
        String requiredRole = requiresRole.value(); // 获取所需的角色
        String token = request.getHeader("token"); // 从请求头获取token
        DecodedJWT verify = JWTUtils.verify(token);
        String userRole = verify.getClaim("roleID").asString();// 从解析后的token中获取角色ID

        // 检查权限
        if (userRole == null || !userRole.equals(requiredRole)) {
            throw new SecurityException("无此权限");
        }

        // 权限通过，继续执行
        return joinPoint.proceed();
    }
}
